<template>
  <div class="product-detail">
    <Navbar />
    <div class="container">
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="error" class="error">{{ error }}</div>
      <div v-else-if="!product" class="not-found">商品不存在或已下架</div>
      <div v-else class="product-content">
        <!-- 商品图片 -->
        <div class="product-images">
          <div class="main-image-container">
            <button class="nav-btn prev-btn" @click="prevImage">&lt;</button>
            <div class="main-image">
              <img :src="getImageUrl(product.images[currentImageIndex])" alt="{{ product.title }}" />
            </div>
            <button class="nav-btn next-btn" @click="nextImage">&gt;</button>
          </div>
          <div class="thumbnails">
            <div v-for="(image, index) in product.images" :key="index" class="thumbnail" :class="{ 'active': index === currentImageIndex }" @click="switchImage(index)">
              <img :src="getImageUrl(image)" alt="{{ product.title }}" />
            </div>
          </div>
        </div>

        <!-- 商品信息 -->
        <div class="product-info">
          <h1 class="title">{{ product.title }}</h1>
          <div class="category">分类: {{ product.category_name }}</div>
          <div class="seller">卖家: {{ product.seller_name }}</div>
          <div class="price">
            <span class="current-price">{{ formatPrice(product.price) }}</span>
            <span v-if="product.original_price" class="original-price">{{ formatPrice(product.original_price) }}</span>
          </div>
          <div class="description">{{ product.description }}</div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <button class="buy-btn" @click="handleBuyNow">立即购买</button>
            <button class="cart-btn">加入购物车</button>
            <button class="contact-btn">联系商家</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import Navbar from '../components/Navbar.vue';
import { ref, onMounted, onUnmounted } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';
import moment from 'moment';

const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000';
const route = useRoute();
const productId = Number(route.params.id);
const product = ref<any>(null);
const loading = ref(true);
const error = ref('');
const currentImageIndex = ref(0);
let carouselInterval: number | null = null;
const CAROUSEL_INTERVAL_MS = 5000; // 轮播间隔时间（毫秒）

// 获取商品详情
const fetchProductDetail = async () => {
  try {
    loading.value = true;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [ProductDetail] 请求商品详情: productId=${productId}`);
    const res = await axios.get(`/api/product/${productId}`);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [ProductDetail] 商品详情响应:`, res.data);

    // 后端返回的数据结构为 { product: { ... } }
    if (res.data && res.data.product && res.data.product.product_id) {
      product.value = res.data.product;
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [ProductDetail] 商品数据已加载:`, product.value);
    } else {
      product.value = null;
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [WARN] [ProductDetail] 未找到商品数据`);
    }
  } catch (err) {
    const e = err as any;
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [ProductDetail] 获取商品详情异常:`, e, e?.response?.data);
    error.value = (e.response && e.response.data && e.response.data.message) || '获取商品详情失败';
  } finally {
    loading.value = false;
  }
};

// 记录浏览历史
const recordBrowseHistory = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return; // 未登录不记录

    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [ProductDetail] 记录浏览历史: productId=${productId}`);
    await axios.post(
      '/api/auth/browse-history',
      { product_id: productId },
      { headers: { 'Authorization': `Bearer ${token}` } }
    );
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [ProductDetail] 浏览历史记录成功`);
  } catch (err) {
    const e = err as any;
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [ProductDetail] 记录浏览历史异常:`, e, e?.response?.data);
    // 浏览历史记录失败不影响主流程
  }
};

// 获取图片URL
const getImageUrl = (imageUrl: string) => {
  if (!imageUrl) return '';
  if (imageUrl.startsWith('http') || imageUrl.startsWith('data:')) return imageUrl;
  if (imageUrl.startsWith('/uploads/')) return API_BASE + imageUrl;
  return API_BASE + '/uploads/' + imageUrl;
};

// 格式化价格 - 处理字符串或数字类型的价格
const formatPrice = (price: string | number) => {
  return '¥' + Number(price).toFixed(2);
};

// 切换到指定图片
const switchImage = (index: number) => {
  currentImageIndex.value = index;
  // 重置轮播计时器
  resetCarouselInterval();
};

// 上一张图片
const prevImage = () => {
  currentImageIndex.value = (currentImageIndex.value - 1 + product.value.images.length) % product.value.images.length;
  // 重置轮播计时器
  resetCarouselInterval();
};

// 下一张图片
const nextImage = () => {
  currentImageIndex.value = (currentImageIndex.value + 1) % product.value.images.length;
  // 重置轮播计时器
  resetCarouselInterval();
};

// 开始轮播
const startCarousel = () => {
  if (product.value && product.value.images.length > 1) {
    carouselInterval = window.setInterval(() => {
      nextImage();
    }, CAROUSEL_INTERVAL_MS);
  }
};

// 重置轮播计时器
const resetCarouselInterval = () => {
  if (carouselInterval) {
    clearInterval(carouselInterval);
  }
  startCarousel();
};

// 停止轮播
const stopCarousel = () => {
  if (carouselInterval) {
    clearInterval(carouselInterval);
    carouselInterval = null;
  }
}

// 立即购买处理函数
const handleBuyNow = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [WARN] [ProductDetail] 用户未登录，跳转至登录页面`);
      // 跳转至登录页面
      window.location.href = '/login';
      return;
    }

    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [ProductDetail] 开始创建订单: productId=${productId}, price=${product.value.price}`);
    // 创建订单
    const orderRes = await axios.post(
      '/api/orders',
      {
        product_id: productId,
        price: product.value.price,
        seller_id: product.value.seller_id
      },
      {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      }
    );

    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [ProductDetail] 订单创建成功:`, orderRes.data);
    const orderId = orderRes.data.order_id;

    // 创建交易记录
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [ProductDetail] 开始创建交易记录: orderId=${orderId}`);
    const transactionRes = await axios.post(
      '/api/transactions',
      {
        order_id: orderId,
        amount: product.value.price,
        payment_method: 'online'
      },
      {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      }
    );

    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [ProductDetail] 交易记录创建成功:`, transactionRes.data);
    // 跳转到支付页面
    window.location.href = `/payment?orderId=${orderId}`;
  } catch (err) {
    const e = err as any;
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [ProductDetail] 立即购买失败:`, e, e?.response?.data);
    alert((e.response && e.response.data && e.response.data.message) || '创建订单失败，请稍后重试');
  }
};

// 页面加载时获取商品详情
onMounted(() => {
  fetchProductDetail().then(() => {
    // 商品加载完成后开始轮播
    startCarousel();
    // 记录浏览历史
    recordBrowseHistory();
  });
});

// 页面卸载时停止轮播
onUnmounted(() => {
  stopCarousel();
});
</script>

<style scoped>
.product-detail {
  min-height: 100vh;
  background-color: #f8fafc;
}

.container {
  max-width: 1200px;
  margin: 80px auto 0;
  padding: 24px 16px;
}

.loading, .error, .not-found {
  text-align: center;
  padding: 48px;
  color: #64748b;
  font-size: 16px;
}

.error {
  color: #ef4444;
}

.product-content {
  display: flex;
  gap: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  padding: 24px;
}

.product-images {
  width: 40%;
}

.main-image-container {
  position: relative;
  width: 100%;
  height: 400px;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 16px;
}

.main-image {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.nav-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  width: 36px;
  height: 36px;
  min-width: 36px;
  min-height: 36px;
  border-radius: 50%;
  font-size: 20px;
  line-height: 36px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  opacity: 0;
  transition: opacity 0.3s, background-color 0.2s;
  box-sizing: border-box;
  padding: 0;
  margin: 0;
  font-family: Arial, sans-serif;
}

.main-image-container:hover .nav-btn {
  opacity: 1;
}

.nav-btn:hover {
  background-color: rgba(0, 0, 0, 0.7);
}

.prev-btn {
  left: 10px;
}

.next-btn {
  right: 10px;
}

.thumbnail.active {
  border-color: #2563eb;
}

.main-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumbnails {
  display: flex;
  gap: 8px;
  overflow-x: auto;
  padding-bottom: 8px;
}

.thumbnail {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid transparent;
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumbnail:hover {
  border-color: #2563eb;
}

.product-info {
  flex: 1;
}

.title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 16px;
  color: #1e293b;
}

.category, .seller {
  color: #64748b;
  margin-bottom: 8px;
  font-size: 14px;
}

.price {
  margin: 16px 0;
}

.current-price {
  font-size: 28px;
  font-weight: 700;
  color: #ef4444;
}

.original-price {
  margin-left: 12px;
  font-size: 16px;
  color: #94a3b8;
  text-decoration: line-through;
}

.description {
  margin: 16px 0;
  padding: 16px;
  background-color: #f8fafc;
  border-radius: 8px;
  color: #334155;
  line-height: 1.6;
}

.action-buttons {
  display: flex;
  gap: 16px;
  margin-top: 24px;
}

.buy-btn, .cart-btn, .contact-btn {
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  border: none;
}

.buy-btn {
  background-color: #ef4444;
  color: #fff;
  flex: 2;
}

.buy-btn:hover {
  background-color: #dc2626;
}

.cart-btn {
  background-color: #2563eb;
  color: #fff;
  flex: 2;
}

.cart-btn:hover {
  background-color: #1d4ed8;
}

.contact-btn {
  background-color: #f8fafc;
  color: #334155;
  border: 1px solid #e2e8f0;
  flex: 1;
}

.contact-btn:hover {
  background-color: #e2e8f0;
}

@media (max-width: 768px) {
  .product-content {
    flex-direction: column;
  }

  .product-images {
    width: 100%;
  }

  .main-image {
    height: 300px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .buy-btn, .cart-btn, .contact-btn {
    width: 100%;
  }
}
</style>